<template>
  <div>
    <el-card body-style="{ padding: '20px' }" >
      <template #header>
        <div class="card-header">
          <el-button type="primary" icon="ele-Plus" @click="add">添加</el-button>
        </div>
      </template>
      <el-table :data="tableData" stripe style="width: 100%" >
        <el-table-column type="index" label="序号" width="80px"/>
        <el-table-column prop="tmName" label="品牌名称"/>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template v-slot:default="{row}">
            <el-image
              :src="row.logoUrl"
              fit="fill"
              :lazy="true"
              style="width: 300px;"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template #default="{row}">
            <el-button type="warning" icon="ele-Edit" @click="update(row)">修改</el-button>
            <el-popconfirm title="Are you sure to delete this?" @confirm="deleteList(row.id)">
              <template #reference>
                <el-button type="danger" icon="ele-Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      v-model:page-size="pageSize"
      :page-count="pageCount"
      :pager-count="5"
      :total="total"
      v-model:current-page="currentPage"
      layout="total,prev, pager, next, sizes, "
      :page-sizes="[3, 5, 7, 9]"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="trademarkList.id ? '修改品牌':'添加品牌'"
    >
      <el-form label-width="120px" :model="trademarkList" :rules="rules" ref="formEle">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademarkList.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="trademarkList.logoUrl" :src="trademarkList.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><ele-Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";
export default defineComponent({
    name:"TradeMark",
})
</script>

<script lang="ts" setup>
import {onMounted,reactive, ref,watch} from "vue";
import {useTrademarkStore} from "@/stores/trademark";
import {ElMessage} from "element-plus";
import type { UploadProps,FormRules ,FormInstance} from 'element-plus'
import type {RecordsType,TrademarkListType} from "@/api/trademark";
import {reqAddTrademark, reqDeleteTrademark, reqUpdateTrademark} from "@/api/trademark";
const trademarkStore = useTrademarkStore()
console.log(trademarkStore)

const tableData = ref<TrademarkListType>([])
const pageSize = ref(3)
const pageCount = ref(0)
const currentPage = ref(1)
const total = ref(0)
const addTrademarkList = async ()=>{
    try {
        await trademarkStore.getTrademarkList(currentPage.value,pageSize.value)
        tableData.value = trademarkStore.trademarkList
        pageCount.value = trademarkStore.pages
        total.value = trademarkStore.total
    }catch (e:any){
        ElMessage.error(e.message)
    }
}
onMounted(()=>{
    addTrademarkList()
})
watch([pageSize,currentPage],()=>{
    addTrademarkList()
})

const dialogVisible =ref(false)
const trademarkList = ref<RecordsType>({
    tmName:"",
    logoUrl:""
})
const imageUrl = ref('')
const formEle = ref<FormInstance>()
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    trademarkList.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
const update = (row:RecordsType)=>{
    formEle.value?.clearValidate()
    dialogVisible.value = true
    trademarkList.value = {...row}
}
const add = ()=>{
    formEle.value?.clearValidate()
    trademarkList.value = {
        tmName:"",
        logoUrl:""
    }
    dialogVisible.value = true
}
const addOrUpdate = async ()=>{
    const re =  await formEle.value?.validate().catch(()=>{return})
    if(!re) return
    try {
       if(trademarkList.value.id){
           await reqUpdateTrademark(trademarkList.value)
           ElMessage.success("修改成功")
       }else {
           await reqAddTrademark(trademarkList.value)
           ElMessage.success("添加成功")
       }
    }catch (e:any){
        ElMessage.error(e.message)
    }
    addTrademarkList()
    dialogVisible.value = false
}
const rules = reactive<FormRules>({
    tmName: [
        {required: true, message: 'Please input Activity name', trigger: 'blur'},
    ],
    logoUrl: [
        {required: true, message: 'Please input Activity name', trigger: 'blur'},
    ],
})
const deleteList = async (id:number)=>{
    try {
        await reqDeleteTrademark(id)
        ElMessage.success("删除成功")
        addTrademarkList()
    }catch (e:any){
        ElMessage.error(e.message)
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

  <style>
  .avatar-uploader .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
  }

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>